package com.javasea.web.jasypt.controller;

import com.alibaba.fastjson.JSON;
import com.javasea.web.jasypt.annotation.EncryptField;
import com.javasea.web.jasypt.annotation.EncryptMethod;
import com.javasea.web.jasypt.model.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/encryptor/")
public class Encryptor {

    @Autowired
    private StringEncryptor stringEncryptor;

    /**
     * http://localhost:9000/encryptor/test
     */
    @GetMapping("test")
    public void encrypt() {
        String encryptStr = stringEncryptor.encrypt("123456");
        System.out.println("加密后的内容：" + encryptStr);
        // 123456加密后的密文
        String decrypt = stringEncryptor.decrypt(encryptStr);
        // 执行解密
        System.out.println("解密后的内容：" + decrypt);
    }

    /**
     * http://localhost:9000/encryptor/insert?name=longxiaonan龙小南
     * {
     *   "userId":"234",
     *   "name":"longxiaonan龙小南",
     *   "mobile":"17612061396",
     *   "address":"广东广州",
     *   "age":18
     * }
     * @param user
     * @param name
     * @return
     */
    @EncryptMethod
    @PostMapping(value = "insert")
    @ResponseBody
    public Object testEncrypt(@RequestBody UserVo user, @EncryptField String name) {
        return insertUser(user, name);
    }

    private UserVo insertUser(UserVo user, String name) {
        // 用户名称：name>>longxiaonan龙小南
        System.out.println("用户名称：name>>" + name);
        // 加密后的数据：user{"address":"l+nGhaGrXOHJrGyRW19MBNAyjl2otJ9t"
        // ,"age":"18","mobile":"mK8aQYXz0sNKmUWby+DZxAqC4zbSuJDp"
        // ,"name":"QN6mQuZvsqoKE1cGJlU+3/5rWkFZDM1Cp7o3vDpxag4=","userId":234}
        System.out.println("加密后的数据：user" + JSON.toJSONString(user));
        return user;
    }
}
